﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace System
{
	public static class Poject
	{
		/// <summary>
		/// 判断布尔数据类型
		/// </summary>
		/// <param name="_this">true ？ false</param>
		/// <param name="val">对比值</param>
		/// <returns></returns>
		public static bool ToBool(this object _this, string val = "")
		{
			try
			{
				if ( _this.Equals("true") || _this.Equals("True") )
					return true;
				else if ( _this.Equals("false") || _this.Equals("False") )
					return false;
				else if ( _this.Equals(val) )
					return true;
				else
					return false;
			}
			catch
			{
				return false;
			}
		}

		/// <summary>
		/// 获取服务器路径
		/// </summary>
		/// <param name="path">服务器路径</param>
		/// <returns></returns>
		public static string ServerPath(this string path)
		{
			try
			{
                return HttpRuntime.AppDomainAppPath.ToString() + path;
            }
			catch ( Exception e )
			{
				return e.Message;
			}
		}

		/// <summary>
		/// 转换Int型
		/// </summary>
		/// <param name="Name">转换字符串</param>
		/// <returns></returns>
		public static int ToInt(this string Name)
		{
			try
			{
				if ( Name == "" || Name == null )
					return 0;
				else
					return int.Parse(Name);
			}
			catch
			{
				return 0;
			}
		}

		/// <summary>
		/// 转换为浮点型
		/// </summary>
		/// <param name="Name">转换参数</param>
		/// <returns></returns>
		public static decimal ToDecimal(this string Name)
		{
			try
			{
				if ( Name == "" || Name == null )
					return 0;
				else
					return Convert.ToDecimal(Name);
			}
			catch
			{
				return 0;
			}
		}

		/// <summary>
		/// 输入JS参数处理
		/// </summary>
		/// <param name="Name">输出内容</param>
		/// <returns></returns>
		public static string ToJs(this string Name)
		{
			if ( Name == "" || Name == null )
				return "";
			else
				return Name.Replace(@"\""", @"""").Replace("\n", "").Replace("\t", "").Replace("\r", "").Replace(@"""", @"\""").Trim();
		}

		/// <summary>
		/// 判断是否相等
		/// </summary>
		/// <param name="_this"></param>
		/// <param name="val">对比值</param>
		/// <returns>返回布尔值</returns>
		public static bool Is<T>(this T _this, T val)
		{
			try
			{
				if ( _this == null && val == null ) return true;

				return _this.Equals(val);
			}
			catch ( Exception e )
			{
				return false;
			}

		}

		/// <summary>
		/// 判断是否不相等
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="_this"></param>
		/// <param name="val"></param>
		/// <returns></returns>
		public static bool IsNot<T>(this T _this, T val)
		{
			try
			{
				if ( _this == null && val == null ) return false;

				return !_this.Equals(val);
			}
			catch ( Exception e )
			{
				return false;
			}

		}

		/// <summary>
		/// 判断字符串最后一位字符 符合条件就过滤
		/// </summary>
		/// <param name="_this"></param>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string IsEndEx(this string _this, string str)
		{
			if ( _this.Length < 1 )
				return "";

			if ( _this.Substring(_this.Length - 1, 1).Is(str) )
				return _this.Substring(0, _this.Length - 1);
			else
				return _this;
		}

		/// <summary>
		/// 判断是否为空
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="_this"></param>
		/// <returns></returns>
		public static bool IsNull<T>(this T _this, bool whether = true)
		{
			if ( _this == null )
				if ( whether )
					return true;
				else
					return false;
			else
				if ( whether )
				return false;
			else
				return true;
		}


		/// <summary>
		/// 获取文章中图片
		/// </summary>
		/// <param name="HTMLStr">过滤字符串</param>
		/// <returns></returns>
		public static string GetImgUrl(this string HTMLStr, int n = 0)
		{
			string str = string.Empty;
			//string sPattern = @"^<img\s+[^>]*>";
			Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
			  RegexOptions.Compiled);
			Match m = r.Match(HTMLStr.ToLower());
			if ( m.Success )
				str = m.Result("${url}");
			if ( String.IsNullOrEmpty(str) )
			{
				if ( n > 0 )
				{
					n++;
					if ( n > 9 )
					{
						if ( n - 10 == 0 )
							return "/Img/m/5.jpg";
						else
							return "/Img/m/" + ( n - 10 ) + ".jpg";
					}
					else
					{
						return "/Img/m/" + n + ".jpg";
					}
				}
				else
					return "";
			}
			return str;
		}

		///   <summary>
		///   去除HTML标记
		///   </summary>
		///   <param   name="ClearHtml">包括HTML的源码</param>
		///   <returns>已经去除后的文字</returns>
		public static string ClearHtml(this string Htmlstring)
		{
			//删除脚本
			Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
			  RegexOptions.IgnoreCase);
			//删除HTML
			Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9",
			  RegexOptions.IgnoreCase);
			Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "",
			  RegexOptions.IgnoreCase);
			Htmlstring.Replace("<", "");
			Htmlstring.Replace(">", "");
			Htmlstring.Replace("\r\n", "");
			Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
			return Htmlstring;
		}

		/// <summary>
		/// 请求验证Token
		/// </summary>
		/// <param name="Token">token</param>
		/// <returns></returns>
		public static int GetDateToken(this int Token)
		{
			int token = Token - 10000;
			DateTime Time = DateTime.Now;
			int Year = Time.Year - 137;
			int Month = Time.Month + 61;
			int Day = Time.Day + 1704;
			int Hour = Time.Hour + 17;
			int a = Year * Month - Day + Hour - token;
			int b = (Day * Month + Year - Hour) * token;
			return ( a + b ) - ( Time.Year * Time.Month + Time.Year );
		}

		/// <summary>
		/// 判断数据库是否处理成功
		/// </summary>
		/// <param name="obj">返回值（int型：OK,string：trr）</param>
		/// <returns></returns>
		public static bool SqlSucceed(this string obj)
		{
			try
			{
				obj.ToInt();
				return true;
			}
			catch ( Exception )
			{
				return false;
			}
		}

		/// <summary>
		/// 获取图片中的所有图片
		/// </summary>
		/// <param name="HTMLStr">过滤字符串</param>
		/// <param name="obj">分隔符 默认：[|]</param>
		/// <returns></returns>
		public static string GetImgAll(this string HTMLStr, string obj = "|")
		{
			StringBuilder Imgs = new StringBuilder();
			Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>", RegexOptions.IgnoreCase);
			string txt = string.Empty;
			MatchCollection col = r.Matches(HTMLStr);
			int i = 0;
			if ( col.Count > 9 ) i = 9;
			else i = col.Count;
			if ( i > 0 )
			{
				for ( int n = 0; n < i; n++ )
				{
					Match m = r.Match(col[n].Value);
					Imgs.Append(m.Result("${url}").Split('>')[0] + "|");
				}
			}
			return Imgs.ToString();
		}

		/// <summary>
		/// 返回表数据
		/// </summary>
		/// <param name="Rows">表内容</param>
		/// <param name="Row">行值</param>
		/// <param name="Col">列值</param>
		/// <returns></returns>
		public static string Value(this DataRowCollection Rows, int Row = 0, int Col = 0)
		{
			try
			{
				return Rows[Row][Col].ToString();
			}
			catch ( Exception e )
			{
				return e.Message;
			}
		}

		/// <summary>
		/// 返回表数据
		/// </summary>
		/// <param name="Rows">表内容</param>
		/// <param name="Row">行值</param>
		/// <param name="Col">列值</param>
		/// <returns></returns>
		public static T Value<T>(this DataRowCollection Rows, string Col, int Row = 0)
		{
			try
			{
				return (T)Rows[Row][Col];
			}
			catch ( Exception e )
			{
				return default(T);
			}
		}

        /// <summary>
		/// 返回表数据
		/// </summary>
		/// <param name="table">表</param>
		/// <param name="Row">行值</param>
		/// <param name="Col">列值</param>
		/// <returns></returns>
        public static T Value<T>(this DataTable table, string Col, int Row = 0)
        {
            return table.Rows.Value<T>(Col,Row);
        }


        /// <summary>
        /// 转换Json数据
        /// </summary>
        /// <param name="Cont"></param>
        /// <returns></returns>
        public static string ToJson<T>(this T Cont)
		{
			return JsonConvert.SerializeObject(Cont);
		}

        /// <summary>
        /// 将数据转换数据模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Cont"></param>
        /// <returns></returns>
        public static T ToEF<T>(this object Cont)
        {
            var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            if (Cont.GetType().Is(typeof(string)))
            {
                try
                {
                    return (T)JsonConvert.DeserializeObject(Cont.ToString(), typeof(T), jSetting);
                }
                catch (Exception e)
                {
                    try
                    {
                        return ((List<T>)JsonConvert.DeserializeObject(Cont.ToString(), typeof(List<T>), jSetting))[0];
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        //throw new ArgumentOutOfRangeException(e.Message + "-----" + ex.Message);
#endif
                        return default(T);
                    }

                }
            }
            else
            {
                string strJson = Cont.ToJson();
                try
                {
                    return (T)JsonConvert.DeserializeObject(strJson, typeof(T), jSetting);
                }
                catch (Exception e)
                {
                    try
                    {
                        return ((List<T>)JsonConvert.DeserializeObject(strJson, typeof(List<T>), jSetting))[0];
                    }
                    catch (Exception ex)
                    {
                        return default(T);
                    }

                }

            }
        }

        /// <summary>
        /// 装换为引索器
        /// </summary>
        /// <param name="Cont"></param>
        /// <returns></returns>
        public static JObject ToObject<T>(this T Cont)
		{

			try
			{
				if ( Cont.GetType().Is(typeof(string)) )
				{
					return JsonConvert.DeserializeObject(Cont.ToString()) as JObject;
				}
				else {
					string strJson = Cont.ToJson();
					return JsonConvert.DeserializeObject(strJson) as JObject;
				}
			}
			catch
			{

				return new JObject();
			}
		}
	}
}